package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.util.TimeUtil;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 智能设备Service业务层处理
 *
 * @author elina
 * @date 2025-10-13
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询智能设备
     *
     * @param id 智能设备主键
     * @return 智能设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询智能设备列表
     *
     * @param device 智能设备
     * @return 智能设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 修改智能设备
     *
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto) {
        // 1. 判断设备名称是否重复
        long count = lambdaQuery().
                eq(Device::getDeviceName, deviceDto.getDeviceName())
                .ne(Device::getId, deviceDto.getId())
                .count();

        if (count > 0) {
            throw new BaseException("设备名称重复");
        }

        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }

        // 2. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .ne(Device::getId, deviceDto.getId())
                .count();

        if (count > 0) {
            throw new BaseException("同一位置只能绑定一个产品");
        }

        // 修改华为云IOT设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        AuthInfoWithoutSecret authInfo = new AuthInfoWithoutSecret();
        authInfo.setSecureAccess(true);
        body.withAuthInfo(authInfo);
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("修改设备名称失败, {}", response);
            throw new BaseException("修改设备名称失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        return deviceMapper.updateById(device);
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId
     * @return
     */
    @Override
    public ArrayList<HashMap<String, Object>> queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("查询设备服务属性失败, {}", response);
            throw new BaseException("查询设备服务属性失败");
        }
        ArrayList<HashMap<String, Object>> result = new ArrayList<>();
        List<DeviceShadowData> shadow = response.getShadow();
        if (!shadow.isEmpty()) {
            DeviceShadowData deviceShadowData = shadow.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            LocalDateTime eventTime = TimeUtil.transform(reported.getEventTime());
            Map<String, Object> properties = (Map<String, Object>) reported.getProperties();
            properties.forEach((key, value) -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("functionId", key);
                map.put("value", value);
                map.put("eventTime", eventTime);
                result.add(map);
            });
        }
        return result;
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isNull(device)) {
            log.error("设备不存在, iotId: {}", iotId);
            throw new BaseException("设备不存在");
        }
        deviceMapper.deleteDeviceById(device.getId());
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            log.error("删除设备失败, {}", response);
            throw new BaseException("删除设备失败");
        }
    }

    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("查询产品详情失败, {}", response);
            throw new BaseException("查询产品详情失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (ObjectUtil.isEmpty(serviceCapabilities)) {
            log.error("产品详情为空, {}", response);
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 每页显示数量
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (ObjectUtil.isNull(response)) {
            log.error("同步产品列表失败");
            throw new BaseException("同步产品列表失败");
        }
        if (response.getHttpStatusCode() != 200) {
            log.error("同步产品列表失败,{}", response);
            throw new BaseException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        // 存储产品信息进Redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    /**
     * 获取所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProducts() {
        String result = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (StringUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(result, ProductVo.class);
    }

    /**
     * 设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo detail(String iotId) {
        // 1. 根据iotId从数据库中查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        // 2. 根据iotId从华为IOT中查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("查询设备详情失败, {}", response);
            throw new BaseException("查询设备详情失败");
        }
        vo.setDeviceStatus(response.getStatus());
        LocalDateTime activeTime = TimeUtil.transform(response.getActiveTime());
        vo.setActiveTime(activeTime);

        return vo;
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 1. 判断设备名称是否重复
        long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0)  {
            throw new BaseException("设备名称重复");
        }
        // 2. 判断设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }

        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        // 3. 判断同一位置是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置只能绑定一个产品");
        }

        // 4. 注册设备到华为IOT
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfo = new AuthInfo();
        // 生成随机密钥
        // 去除横线
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.withNodeId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withAuthInfo(authInfo)
                .withProductId(deviceDto.getProductKey());
        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            log.error("设备注册失败，{}",  response);
            throw new BaseException("设备注册失败");
        }
        String deviceId = response.getDeviceId();
        deviceDto.setIotId(deviceId);
        Device device = new Device();
        device.setSecret(secret);
        BeanUtil.copyProperties(deviceDto, device);
        // 5. 保存数据库
        save(device);
    }


}
